package com.cyz.web.app.asyncTool.test;

import com.cyz.web.app.asyncTool.tools.executor.Async;
import com.cyz.web.app.asyncTool.tools.executor.timer.SystemClock;
import com.cyz.web.app.asyncTool.tools.wrapper.WorkerWrapper;

import java.util.concurrent.ExecutionException;

public class Demo01 {

    //三个任务同时并发执行
    private void test1() {
        ParWork parWork = new ParWork();
        ParWork1 parWork1 = new ParWork1();
        ParWork2 parwork2 = new ParWork2();


        WorkerWrapper<String, String> wrapper = new WorkerWrapper.Builder<String, String>()
                .worker(parWork).callback(parWork).param("0").build();

        WorkerWrapper<String, String> wrapper1 = new WorkerWrapper.Builder<String, String>()
                .worker(parWork1).callback(parWork1).param("1").build();

        WorkerWrapper<String, String> wrapper2 = new WorkerWrapper.Builder<String, String>()
                .worker(parwork2).callback(parwork2).param("2").build();

        long now = SystemClock.now();
        System.out.println("begin-" + now);
        try {
            Async.beginWork(1500, wrapper, wrapper1, wrapper2);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(wrapper.getWorkResult());

        System.out.println("end-" + SystemClock.now());
        System.err.println("cost-" + (SystemClock.now() - now));
        System.out.println(Async.getThreadCount());
        Async.shutDown();
    }

    //
    private void test2() {
        ParWork parWork = new ParWork();
        ParWork1 parWork1 = new ParWork1();
        ParWork2 parwork2 = new ParWork2();


        WorkerWrapper<String, String> wrapper1 = new WorkerWrapper.Builder<String, String>()
                .worker(parWork1).callback(parWork1).param("1").build();

        WorkerWrapper<String, String> wrapper2 = new WorkerWrapper.Builder<String, String>()
                .worker(parwork2).callback(parwork2).param("2").build();

        WorkerWrapper<String, String> wrapper = new WorkerWrapper.Builder<String, String>()
                .worker(parWork).next(wrapper1, wrapper2).param("today is nice").callback(parWork).build();

        long now = SystemClock.now();
        System.out.println("begin-" + now);
        try {
            Async.beginWork(1500, wrapper);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(wrapper.getWorkResult());

        System.out.println("end-" + SystemClock.now());
        System.err.println("cost-" + (SystemClock.now() - now));
        System.out.println(Async.getThreadCount());
        Async.shutDown();
    }

    public static void main(String[] args) {
        Demo01 d = new Demo01();
        d.test2();


    }

}
